<?php

namespace App\Listeners;

use App\Constant;
use App\Events\OrderCreate;
use App\Events\RechargeComplete;
use App\Models\BalanceLogModel;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

class CalculateOrderProfit
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderCreate  $event
     * @return void
     */
    public function handle(OrderCreate $event)
    {
        //
        $order_model = $event->order;
        $detail_list = $order_model->orderDetails;
        $rebate_money = 0;
        foreach ($detail_list as $k => $v) {
            $real_product = $v->product;
            $raw_product = $v->product->referrel;
            if(!$raw_product) {
                Log::error("{$order_model->id}#{$v->id}#无源头商品");
            }
            $money = $real_product->unit_price - ($raw_product ? $raw_product->unit_price : 0);
            Log::error("{$order_model->id}#{$v->id}#{$money}");
            if($money > 0) {
                $rebate_money += $money;
            }
        }
        $order_model->fill(['rebate_money' => $rebate_money])->save();

    }
}
